/*
 * Copyright 2007. Mount Sinai Hospital, Toronto, Canada.
 * 
 * Licensed under the GNU Lesser General Public License, Version 2. You
 * can find a copy of the license at:
 * 
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
 * 
 * IN NO EVENT SHALL MOUNT SINAI HOSPITAL BE LIABLE TO ANY PARTY FOR DIRECT, 
 * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST 
 * PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, 
 * EVEN IF MOUNT SINAI HOSPITAL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
 * DAMAGE.
 * 
 * MOUNT SINAI HOSPITAL SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTIES OF 
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND 
 * ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". 
 * MOUNT SINAI HOSPITAL HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, 
 * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. 
 */
package com.sinai.mshab.client.ui.basic;

/**
 * A specification of what characters should be inserted at what positions
 * during data entry to a field.
 * 
 * @author serge
 * 
 */
public class Mask {

	private String mask;

	public String getText() {
		return mask;
	}

	/**
	 * Creates a new mask. Create masks like: mmm-mmm/mmm ignores 'm' and puts -
	 * and / at the right indexies.
	 */
	public Mask(String m) {
		mask = m;
	}

	/**
	 * Inserts the right character at the right time.
	 * 
	 * @param s
	 */
	public String applyMask(String s) {

		int from = 0;

		// going through the mask
		for (int i = 0; i < mask.length(); i++) {

			char mask_curr = mask.charAt(i);

			// come across an insert char in the mask
			if (mask_curr != 'm') {

				// find where this character appears in the string (if at all)
				int first_location = s.indexOf(mask_curr, from + 1);

				if (first_location == -1) {
					s = insert(s, mask_curr, i);
					from = i;
				} else if (first_location == i) {
					// do nothing, it's already there where it needs to be.
					from = i;
				} else if (first_location < i) {
					// user is doing something weird, like deleting data, it's
					// already there, modify lookup location
					from = first_location;
				} else if (first_location > i) {
					s = insert(s, mask_curr, i);
					from = i;
				}
			}
		}

		return s;
	}

	public String insert(String s, char c, int index) {

		// if its impossible
		if (s.length() < index) {
			return s;
		}

		String before = s.substring(0, index);
		String after = s.substring(index);
		return before + c + after;
	}
}
